// pages/goods/share.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderDetail:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '图片生成中...',
      mask:true
    })
    //获取商品详情
    that.getDetail(options.id);

    wx.request({
      url: app.d.hostUrl + 'api/car/get_access',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'mchnt': getApp().d.mchnt 
      },
      success: function (res) {
        wx.request({
          url: getApp().d.hostUrl + 'api/car/get_share_img',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'mchnt': getApp().d.mchnt 
          },
          data:{
            path: 'pages/my/index?id=' + options.id,
            imgurl: that.data.orderDetail.main_image,
            access_token: res.data.data
          },
          success:function(r){
            that.opdraw(r.data.data.image2, r.data.data.image1);
          }
        })
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络请求异常',
          duration: 2000
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },


  //获取详情
  getDetail: function (id) {
    var that = this;
    wx.request({
      url: app.d.hostUrl + 'api/car/get_car',
      data: {
        id: id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'mchnt': getApp().d.mchnt 
      },
      success: function (res) {
        that.setData({
          orderDetail: res.data.data,
        });
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络请求异常',
          duration: 2000
        });
      }
    });
  },



  /**
 * 绘制分享的图片
 * @param goodsPicPath 商品图片的本地链接
 * @param qrCodePath 二维码的本地链接
 */
  drawSharePic: function (goodsPicPath, qrCodePath) {
    var that = this;
    //y方向的偏移量，因为是从上往下绘制的，所以y一直向下偏移，不断增大。
    const title = that.data.orderDetail.type + ' ' + that.data.orderDetail.license_time;
    const title1 = '批发价：' + that.data.orderDetail.money+'万元';
    const title2 = that.data.orderDetail.describe;
    const codeText = '长按图片,进去小程序查看更多车辆信息';

    const canvasCtx = wx.createCanvasContext('myCanvas');

    //绘制背景
    canvasCtx.setFillStyle('white');
    canvasCtx.fillRect(0,0, 390, 700);

    //绘制分享的标题文字
    canvasCtx.setFontSize(20);
    canvasCtx.setFillStyle('#000');
    canvasCtx.setTextAlign('left');
    canvasCtx.fillText(title, 10, 40);

    //绘制分享的第二行标题文字
    canvasCtx.setFontSize(14);
    canvasCtx.setTextAlign('left');
    canvasCtx.setFillStyle('red')
    canvasCtx.fillText(title1, 10, 60);

    //绘制分享的第二行标题文字
    canvasCtx.setFontSize(14);
    canvasCtx.setTextAlign('left');
    canvasCtx.setFillStyle('#000')
    canvasCtx.fillText(title2, 10,80);

    var width = 375;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res);
        width = res.windowWidth;
      },
    })
    console.log(width);

    //绘制商品图片
    canvasCtx.drawImage(goodsPicPath, 0,110, width,200);

    //绘制最底部文字
    canvasCtx.setFontSize(12);
    canvasCtx.setFillStyle('#333333');
    canvasCtx.setTextAlign('center');
    canvasCtx.fillText(codeText, width/2, 500);

    //绘制二维码
    canvasCtx.drawImage(qrCodePath, (width-160)/2, 320, 160, 160);
    canvasCtx.draw();
    
    //绘制之后加一个延时去生成图片，如果直接生成可能没有绘制完成，导出图片会有问题。
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 390,
        height: 600,
        destWidth: 390,
        destHeight: 600,
        canvasId: 'myCanvas',
        success: function (res) {
          console.log('分享本地文件==>'+res.tempFilePath)
          that.setData({
            shareImage: res.tempFilePath,
            showSharePic: true
          });
          wx.showToast({
            title: '已保存相册',
          })
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res)
          wx.hideLoading();
        }
      })
    }, 2000);
  },

  opdraw: function (goodsPicPath, qrCodePath){
    var that = this;
    /* promise可以忽略 是用来改善异步回调执行顺序 与本功能没有大的关系 */
    let promise1 = new Promise(function (resolve, reject) {
      /* 获得要在画布上绘制的图片 */
      wx.getImageInfo({
        src: goodsPicPath,
        success: function (res) {
          resolve(res);
        }
      })
    });
    
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: qrCodePath,
        success: function (res) {
          resolve(res);
        }
      })
    });

    /* 图片获取成功才执行后续代码 */
    Promise.all(
      [promise1, promise2]
    ).then(res => {
      //y方向的偏移量，因为是从上往下绘制的，所以y一直向下偏移，不断增大。
      const title = that.data.orderDetail.type + ' ' + that.data.orderDetail.license_time;
      const title1 = '批发价：' + that.data.orderDetail.money + '万元';
      const title2 = that.data.orderDetail.describe;
      const codeText = '长按图片,进去小程序查看更多车辆信息';

      const canvasCtx = wx.createCanvasContext('myCanvas');

      //绘制背景
      canvasCtx.setFillStyle('white');
      canvasCtx.fillRect(0, 0, 390, 700);

      //绘制分享的标题文字
      canvasCtx.setFontSize(20);
      canvasCtx.setFillStyle('#000');
      canvasCtx.setTextAlign('left');
      canvasCtx.fillText(title, 10, 40);

      //绘制分享的第二行标题文字
      canvasCtx.setFontSize(14);
      canvasCtx.setTextAlign('left');
      canvasCtx.setFillStyle('red')
      canvasCtx.fillText(title1, 10, 60);

      //绘制分享的第二行标题文字
      canvasCtx.setFontSize(14);
      canvasCtx.setTextAlign('left');
      canvasCtx.setFillStyle('#000')
      canvasCtx.fillText(title2, 10, 80);

      var width = 375;
      wx.getSystemInfo({
        success: function (res) {
          width = res.windowWidth;
        },
      })
      
      //绘制商品图片
      canvasCtx.drawImage(res[0].path, 0, 110, width, 200);

      //绘制最底部文字
      canvasCtx.setFontSize(12);
      canvasCtx.setFillStyle('#333333');
      canvasCtx.setTextAlign('center');
      canvasCtx.fillText(codeText, width / 2, 500);

      //绘制二维码
      canvasCtx.drawImage(res[1].path, (width - 160) / 2, 320, 160, 160);
      canvasCtx.draw();

      //绘制之后加一个延时去生成图片，如果直接生成可能没有绘制完成，导出图片会有问题。
      setTimeout(function () {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 390,
          height: 600,
          destWidth: 390,
          destHeight: 600,
          canvasId: 'myCanvas',
          success: function (res) {
            that.setData({
              shareImage: res.tempFilePath,
              showSharePic: true
            })
            wx.hideLoading();
          },
          fail: function (res) {
            wx.hideLoading();
          }
        })
      }, 2000);
    })
  },


  show:function(){
    var that = this;
    wx.previewImage({
      current: '1', // 当前显示图片的http链接
      urls: [that.data.shareImage] // 需要预览的图片http链接列表
    })
  }
})